package com.mcb_wxc.util;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class Mail {
	// 定义发件人、收件人、主题等
	private String to = "";
	private String from = "";
	private String host = "";
	private String subject = "";
	boolean isAuth = false;
	private String username;
	private String pwd;
	private String cc = ""; 
	private String bcc = "";
	
	// 用于保存发送附件的文件名的集合
	List<String> file = new ArrayList<String>();

	// 不需要认证
	public Mail(String to, String from, String smtpServer, String subject, String cc, String bcc) {
		this.to = to.trim();
		this.from = from.trim();
		this.host = smtpServer.trim();
		this.subject = subject.trim();
		this.cc = cc.trim();
		this.bcc = bcc.trim();
	}

	// 需要认证
	public Mail(String to, String from, String smtpServer, String subject, String username, String pwd, String cc, String bcc) {
		this.to = to.trim();
		this.from = from.trim();
		this.host = smtpServer.trim();
		this.subject = subject.trim();
		this.username = username.trim();
		this.pwd = pwd;
		this.isAuth = true;
		this.cc=cc.trim();
		this.bcc=bcc.trim();
	}

	// 该方法用于收集附件名
	public void attachfile(String fname) {
		file.add(fname);
	}
	
	/**
	 * 发送邮件
	 * @return
	 */
	public boolean startSend() {
		return startSend("");
	}

	/**
	 * 发送邮件
	 * @param content
	 * @return
	 */
	public boolean startSend(String content) {
		return startSend(content, null);
	}

	// 开始发送信件的方法
	public boolean startSend(String content, String contentType) {
		Session session = null;
		// 创建Properties对象
		Properties props = System.getProperties();
		// 创建信件服务器
		props.put("mail.smtp.host", host);
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.port", "465");
		props.put("mail.smtp.starttls.enable", "true");
		props.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");  
		// 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类。默认值为true。  
		//props.setProperty("mail.smtp.socketFactory.fallback", "false");  
		// 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口。  
		props.setProperty("mail.smtp.socketFactory.port", "465");  
		if (isAuth) {
			if(host.equals("smtp.gmail.com")) {
				props.put("mail.smtp.port", "587"); 
				props.put("mail.smtp.starttls.enable", "true");
			}
			props.setProperty("mail.smtp.auth", "true"); 
			// 得到默认的对话对象
//			session = Session.getDefaultInstance(props, new Authenticator() {
//			session = Session.getDefaultInstance(props, null);
			session = Session.getInstance(props, new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, pwd);
				}
			});
		} else {
			session = Session.getDefaultInstance(props, null);
		}
		try {
			// 创建一个消息，并初始化该消息的各项元素
			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(from));
			InternetAddress[] recipients = toIA(to);
			if(recipients == null){
				throw new RuntimeException("收件人不能为空！");
			}else{
				msg.setRecipients(Message.RecipientType.TO, recipients);
			}
			//抄送
			InternetAddress[] recipientCC = toIA(cc);
			msg.setRecipients(Message.RecipientType.CC, recipientCC);
			
			//密抄
			InternetAddress[] recipientBCC = toIA(bcc);
			msg.setRecipients(Message.RecipientType.BCC, recipientBCC);
			
			msg.setSubject(subject);
			// 后面的BodyPart将加入到此处创建的Multipart中
			Multipart mp = new MimeMultipart();
			// 检查序列中是否还有更多的对象
			for (String filename : file) {
				MimeBodyPart mbp = new MimeBodyPart();
				// 得到数据源
				FileDataSource fds = new FileDataSource(filename);
				// 得到附件本身并至入BodyPart
				mbp.setDataHandler(new DataHandler(fds));
				// 得到文件名同样至入BodyPart
				mbp.setFileName(fds.getName());
				mp.addBodyPart(mbp);
			}
	
			// 移走集合中的所有元素
			file.removeAll(file);
			if (contentType != null) {
				MimeBodyPart mbp = new MimeBodyPart();
				mbp.setContent(content, contentType);
				mp.addBodyPart(mbp);
			}
			// Multipart加入到信件
			msg.setContent(mp);
			if (contentType == null) {
				msg.setText(content);
			}
			// 设置信件头的发送日期
			msg.setSentDate(new Date());
			// 发送信件
			Transport.send(msg);
		} catch (MessagingException mex) {
			mex.printStackTrace();
			Exception ex = null;
			if ((ex = mex.getNextException()) != null) {
				ex.printStackTrace();
			}
			return false;
		} 
		finally{
			session = null;
		}
		return true;
	}
	
	private static InternetAddress[] toIA(String addr) throws AddressException {
		if(addr == null || addr.trim().equals("")) {
			return null;
		}	
		String[] parts = addr.split(";");
		List<InternetAddress> ias = new ArrayList<InternetAddress>();
		for(int i=0; i<parts.length; i++){
			if (parts[i].trim().equals("")) continue;
			ias.add(new InternetAddress(parts[i].trim()));
		}
		InternetAddress[] addrs = new InternetAddress[ias.size()];
		return ias.toArray(addrs);
//		if(addr.indexOf(";")>0){
//			msg.setRecipients(Message.RecipientType.TO, ia);
//		}else{
//			msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
//		}
	}
	
	public static void main(String[] args) throws Exception {
		//for (int i = 0; i < 10000; i++) {
			//System.out.println("now sending mail : " + i);
			Mail m = new Mail("975118135@qq.com", "no-reply@xfj100.com", "smtp.mxhichina.com", "test-no-auth", "no-reply@xfj100.com", "Aleck123", "", "");
			m.startSend();
			Thread.sleep(1000);
		//}
	}
	
}
